﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;
using System.Configuration;
using System.Diagnostics;

namespace MINERP.COM
{
    public class UDPMessage
    {
        private static bool isNeedReboot;
        private static string _receiveMsgFromServer;
        public static List<string> GetServerInfo()
        {
            int recv = 0;
            byte[] data = new byte[1024];
            List<string> list = new List<string>();

            //构建TCP 服务器

            //得到本机IP，设置TCP端口号         
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8001);
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            newsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
            //绑定网络地址
            newsock.Bind(ipep);
            //得到客户机IP
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)(sender);
            string strTemp = "";
            DateTime nowTime = DateTime.Now;

            while (((TimeSpan)(DateTime.Now - nowTime)).Seconds < 6)
            {
                Application.DoEvents();
                try
                {
                    recv = newsock.ReceiveFrom(data, ref Remote);
                }
                catch
                {
                    MessageBox.Show("未见有服务器启动,请与管理员联系", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Environment.Exit(0);
                }
                string strData = Encoding.Unicode.GetString(data, 0, recv);

                strTemp = list.Find(delegate(string a)
                {
                    if (a.Equals(strData))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                });
                if (strTemp == null)
                {
                    list.Add(strData);
                }



            }

            newsock.Close();
            return list;
        }

        public static void Application_ApplicationExit(object sender, EventArgs e)
        {
            //程序正常结否时处理是否需要重启
            if (isNeedReboot)
            {
                Process.Start(Application.ExecutablePath);
            }
        }

        /// <summary>
        /// 检查程序是否多次运行
        /// </summary>
        public static bool CheckMultilStart()
        {
            bool isAppRunning = false;
            System.Threading.Mutex mutex = new System.Threading.Mutex(
                true,
                //System.Diagnostics.Process.GetCurrentProcess().ProcessName,
                "MINERP.AutoOrder_Fuji",
                out isAppRunning);

            if (isAppRunning)
            {
                MessageBox.Show("本程序已运行，请不要重复运行！");
                Environment.Exit(1);
            }

            return isAppRunning;
        }

        /// <summary>
        /// 每次启动时处理收到的信息
        /// </summary>
        public static bool ProcessReceiveMsg(bool isNeedCheckIp)
        {
            _receiveMsgFromServer = GetServerInfo()[0];
            isNeedReboot = false;
            List<string> recMsgList = _receiveMsgFromServer.Split(new char[] { '|' }).ToList();
            string curConnStr = ConfigurationManager.ConnectionStrings["sqlCon"].ConnectionString;
            //string curConnStr =;

            string serverConnStr = recMsgList[0];
            if (!serverConnStr.Equals(curConnStr))//如果不等
            {
                ModifyConfig(serverConnStr);
                isNeedReboot = true;
            }
            if (isNeedCheckIp)
            {
                //检查IP地址是否相等
                CheckIpIsModify(recMsgList[1]);
            }
            if (isNeedReboot)
            {
                Application.Exit();
                return false;
            }

            return true;

        }

        private static void CheckIpIsModify(string serverName)
        {
            int startIndex = serverName.IndexOf("(");
            string ip = serverName.Substring(startIndex + 1, serverName.Length - startIndex - 2);
            try
            {
                if (ConfigurationManager.AppSettings["RemoteIP"] != null && !ConfigurationManager.AppSettings["RemoteIP"].Equals(ip))
                {
                    ModifyConfigurationOP.SetConfig("RemoteIP", ip);
                    isNeedReboot = true;
                }
            }
            catch (Exception e)
            {
                throw e;
            }

        }


        //修改连接配置
        private static void ModifyConfig(string strConn)
        {
            //修改Printing
            //ConnectionStringSettings mySettings1 = new ConnectionStringSettings("Printing", strConn, "System.Data.SqlClient");
            //System.Configuration.Configuration config1 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //if (config1 != null)
            //{
            //    config1.ConnectionStrings.ConnectionStrings.Remove("Printing");
            //    config1.ConnectionStrings.ConnectionStrings.Add(mySettings1);
            //    config1.Save(ConfigurationSaveMode.Minimal);
            //    ConfigurationManager.RefreshSection("ConnectionStrings");
            //}


            ////修改fffff
            //ConnectionStringSettings mySettings2 = new ConnectionStringSettings("fffff", strConn, "System.Data.SqlClient");
            //System.Configuration.Configuration config2 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //if (config2 != null)
            //{
            //    config2.ConnectionStrings.ConnectionStrings.Remove("fffff");
            //    config2.ConnectionStrings.ConnectionStrings.Add(mySettings2);
            //    config2.Save(ConfigurationSaveMode.Minimal);
            //    ConfigurationManager.RefreshSection("ConnectionStrings");
            //}


            //修改sqlCon

            ConnectionStringSettings mySettings3 = new ConnectionStringSettings("sqlCon", strConn, "System.Data.SqlClient");
            System.Configuration.Configuration config3 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config3 != null)
            {
                config3.ConnectionStrings.ConnectionStrings.Remove("sqlCon");
                config3.ConnectionStrings.ConnectionStrings.Add(mySettings3);
                config3.Save(ConfigurationSaveMode.Minimal);
                ConfigurationManager.RefreshSection("ConnectionStrings");
            }

            //修改newSampleYPDBEntities
            string connectionString = ConfigurationManager.ConnectionStrings["newSampleYPDBEntities"].ToString();
            string strConn1 = strConn + ";";
            string strConn2 = string.Empty;
            strConn2 = connectionString.Substring(connectionString.IndexOf("MultipleActiveResultSets"));
            string str = connectionString.Substring(0, connectionString.IndexOf("Data Source"));
            connectionString = str + strConn1 + strConn2;
            ConnectionStringSettings mySettings = new ConnectionStringSettings("newSampleYPDBEntities", connectionString, "System.Data.EntityClient");
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings.Remove("newSampleYPDBEntities");
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            config.Save(ConfigurationSaveMode.Minimal);
            ConfigurationManager.RefreshSection("ConnectionStrings");
        }
        public static void EncryptConfiguration()
        {
            // 使用什么类型的加密

            string provider = "RsaProtectedConfigurationProvider";

            Configuration config = null;

            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // 加密连接字符串

            ConfigurationSection section = config.ConnectionStrings;

            if ((section.SectionInformation.IsProtected == false) && (section.ElementInformation.IsLocked == false))
            {
                section.SectionInformation.ProtectSection(provider);

                section.SectionInformation.ForceSave = true;

                config.Save(ConfigurationSaveMode.Full);

            }
        }
    }
}
